import axios, { AxiosResponse } from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || 'http://localhost:8000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token等
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  (error) => {
    console.error('API Error:', error);
    
    if (error.response) {
      // 服务器返回错误状态码
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          // 未授权，可以跳转到登录页
          break;
        case 403:
          // 禁止访问
          break;
        case 404:
          // 资源不存在
          break;
        case 500:
          // 服务器内部错误
          break;
        default:
          break;
      }
      
      return Promise.reject({
        status,
        message: data?.detail || data?.message || '请求失败',
        data
      });
    } else if (error.request) {
      // 请求已发出但没有收到响应
      return Promise.reject({
        status: 0,
        message: '网络连接失败，请检查网络设置',
        data: null
      });
    } else {
      // 请求配置出错
      return Promise.reject({
        status: 0,
        message: '请求配置错误',
        data: null
      });
    }
  }
);

// API服务类
export const apiService = {
  // GET请求
  get: async (url: string, params?: any) => {
    try {
      const response = await api.get(url, { params });
      return response;
    } catch (error) {
      throw error;
    }
  },

  // POST请求
  post: async (url: string, data?: any) => {
    try {
      const response = await api.post(url, data);
      return response;
    } catch (error) {
      throw error;
    }
  },

  // PUT请求
  put: async (url: string, data?: any) => {
    try {
      const response = await api.put(url, data);
      return response;
    } catch (error) {
      throw error;
    }
  },

  // DELETE请求
  delete: async (url: string) => {
    try {
      const response = await api.delete(url);
      return response;
    } catch (error) {
      throw error;
    }
  },

  // 文件上传
  upload: async (url: string, file: File, onProgress?: (progress: number) => void) => {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await api.post(url, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          if (onProgress && progressEvent.total) {
            const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            onProgress(progress);
          }
        },
      });

      return response;
    } catch (error) {
      throw error;
    }
  },
};

export default apiService;
